1. Basics


Load packages and pull data

library(readr)
library(tidyverse)
## -- Attaching packages ----------------------------------------------------------------------------------------- tidyverse 1.2.1 --
## v ggplot2 3.0.0     v purrr   0.2.5
## v tibble  1.4.2     v dplyr   0.7.7
## v tidyr   0.8.1     v stringr 1.3.1
## v ggplot2 3.0.0     v forcats 0.3.0
## -- Conflicts -------------------------------------------------------------------------------------------- tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()
library(leaflet)
cluster_demog<-read_csv(
"http://ec2-54-235-58-226.compute-1.amazonaws.com/storage/f/2014-02-23T17%3A11%3A51.737Z/dc-neighborhood-cluster-demographics.csv")
## Parsed with column specification:
## cols(
##   .default = col_integer(),
##   neighborhood_cluster = col_character(),
##   Short_Name = col_character(),
##   Full_Name = col_character(),
##   lon_ctr = col_double(),
##   lat_ctr = col_double(),
##   Population = col_character(),
##   `Pct_chng_pop,_1980_to_1990` = col_double(),
##   `Pct_chng_pop,_1990_to_1900` = col_double(),
##   `Pct_chng_pop,_2000_to_2010` = col_double(),
##   Children = col_character(),
##   `Pct_children,_1980` = col_double(),
##   `Pct_children,_1990` = col_double(),
##   `Pct_children,_2000` = col_double(),
##   `Pct_children,_2010` = col_double(),
##   `Pct_chng_child_pop,_1980_to_90` = col_double(),
##   `Pct_chng_child_pop,_1990_to_00` = col_double(),
##   `Pct_chng_child_pop,_2000_to_10` = col_double(),
##   `Race/Ethnicity` = col_character(),
##   `Pct_black_non-Hispanic,_1990` = col_double(),
##   `Pct_black_non-Hispanic,_2000` = col_double()
##   # ... with 168 more columns
## )
## See spec(...) for full column specifications.

Blank Map

leaflet( data = cluster_demog ) %>%
    addTiles() 

Add Markers

Add markers with addMarkers(), specifying the columns for latitude, lat, and longitude, lng, at minimum.

leaflet( data = cluster_demog ) %>%
    
    addTiles() %>%
    
    addMarkers(   lng = cluster_demog$lon_ctr      ### !!! ### 
                , lat = cluster_demog$lat_ctr        ### !!! ### 
                )                                  ### !!! ### 

Change Map “Tiles”

To do this, we swap the default addTiles() for addProviderTiles(providers$name_of_desired_tile). You can preview the built-in Leaflet tiles here.

leaflet( data = cluster_demog ) %>%
    
    addProviderTiles( providers$CartoDB.Positron ) %>%    ### !!! ### 
   
    addMarkers(   lng = cluster_demog$lon_ctr 
                , lat=cluster_demog$lat_ctr 
                )
leaflet( data = cluster_demog ) %>%
    
    addProviderTiles( providers$NASAGIBS.ViirsEarthAtNight2012 ) %>%    ### !!! ### 
    
    addMarkers(   lng = cluster_demog$lon_ctr 
                , lat = cluster_demog$lat_ctr 
                )

Set the initial corrdinates and zoom level

The setView() utility function with three arguments: latitude, lat, and longitude, lng, and the zoom level, zoom.

 ### !!! ### 
leaflet( data = cluster_demog ) %>% 
    setView(lng = -77.0369, lat = 38.9072,  zoom=04) %>%           ### !!! ### 
    
    addProviderTiles( providers$NASAGIBS.ViirsEarthAtNight2012 ) %>%   
    
    addMarkers(   lng = cluster_demog$lon_ctr 
                , lat = cluster_demog$lat_ctr 
                )

2. Pop-ups


Add Pop-ups

To do this, we add popup = desired_popup_data_here as an argument into addMarkers().

leaflet( data = cluster_demog ) %>%
    
    addProviderTiles(providers$CartoDB.Positron) %>%
    
    addMarkers(   lng = cluster_demog$lon_ctr 
                , lat=cluster_demog$lat_ctr 
                , popup =  cluster_demog$Full_Name       ### !!! ###     
                )  

Add More Info to Pop-ups

To do this, we just simply paste() the information together

 leaflet( data = cluster_demog ) %>%
    
    addProviderTiles(providers$CartoDB.Positron) %>%
    
    addMarkers(   lng = cluster_demog$lon_ctr 
                , lat=cluster_demog$lat_ctr 
                , popup =  paste(   cluster_demog$Full_Name                ### !!! ###     
                                  , cluster_demog$neighborhood_cluster ,sep=" "     ### !!! ### 
                                  )                                        ### !!! ### 
                )  

Format Pop-ups

Let’s separate the pop-up details with a line break. To do this, assign the sep argument of paste() to sep = "<br/>"

 leaflet( data = cluster_demog ) %>%
    
    addProviderTiles(providers$CartoDB.Positron) %>%
    
    addMarkers(   lng = cluster_demog$lon_ctr 
                , lat=cluster_demog$lat_ctr 
                , popup =  paste(   sep = "<br/>"                     ### !!! ###     
                                  , cluster_demog$Full_Name          
                                  , cluster_demog$neighborhood_cluster 
                                  
                                  )
                )  

3. Markers


From Plain Markers to Circle Markers

To do this, we will use addCircleMarkers() instead of addMarkers().

leaflet( data = cluster_demog ) %>%
    
    addProviderTiles(providers$CartoDB.Positron) %>%
    
    addCircleMarkers(   lng = cluster_demog$lon_ctr                      ### !!! ###
                , lat=cluster_demog$lat_ctr 
                , popup =  paste(   sep = "<br/>"                         
                                  , cluster_demog$Full_Name          
                                  , cluster_demog$neighborhood_cluster 
                                  
                                  )
                )  

Circle Marker Radius

 leaflet( data = cluster_demog ) %>%
    
    addProviderTiles(providers$CartoDB.Positron) %>%
    
    addCircleMarkers(   lng = cluster_demog$lon_ctr                      ### !!! ###
                , lat=cluster_demog$lat_ctr 
                , popup =  paste(   sep = "<br/>"                         
                                  , cluster_demog$Full_Name          
                                  , cluster_demog$neighborhood_cluster 
                                  )
                , radius = cluster_demog$`Population,_2010`
                )  

Ew. Circles are so large that they fill the map!

Circle Marker Radius

 leaflet( data = cluster_demog ) %>%
    
    addProviderTiles(providers$CartoDB.Positron) %>%
    
    addCircleMarkers(   lng = cluster_demog$lon_ctr                     
                , lat=cluster_demog$lat_ctr 
                , popup =  paste(   sep = "<br/>"                         
                                  , cluster_demog$Full_Name          
                                  , cluster_demog$neighborhood_cluster 
                                  )
                , radius = cluster_demog$`Population,_2010`/5000              ### !!! ###
                )  

4. Choropleths, GeoJSON, Spatial Polygons


Oh My!

You might want this later: https://rstudio.github.io/leaflet/choropleths.html

Using package geojsonio

#library(geojsonio)
cluster_outlines<-geojsonio::geojson_read("http://data.codefordc.org/dataset/8c0a1a57-8abf-4a29-abbb-ee2b890a878e/resource/3f9ce2d9-b438-4dab-a232-694cb80c7964/download/neighborhoodclusters.geojson", what = "sp")

cluster_outlines$Cluster_num<-as.numeric(grep("([0-9]+).*$",  as.character(cluster_outlines$NAME)))
leaflet(cluster_outlines)  %>%
  addTiles() %>% 
    addPolygons()

Color between the lines

Choosing to color by 2010 population.

#summary(cluster_demog$`Population,_2010`)
cluster_outlines@data<-merge(cluster_outlines@data, cluster_demog, by="Cluster_num")

cut_offs<-data.frame(bins=quantile(cluster_outlines$`Population,_2010`, c(0,.2,.3,.4,.5,.6,.7,.8,1)))
bins <-c(0,cut_offs$bins)
pal <- colorBin("YlOrRd", domain = cluster_outlines$`Population,_2010`, bins = bins)



leaflet(cluster_outlines)  %>%
  addTiles() %>% 
    addPolygons(fillColor = ~pal(`Population,_2010`)                 ### !!! ###
     )

Make it easier to see

leaflet(cluster_outlines)  %>%
  addTiles() %>% 
   addPolygons(fillColor = ~pal(`Population,_2010`)  
      ,weight = 2,                                       ### !!! ###
  opacity = 1,                                            ### !!! ###
  color = "white",                                        ### !!! ###
#  dashArray = "3",
  fillOpacity = 0.7)

Another option

leaflet(cluster_outlines)  %>%
  addProviderTiles(providers$CartoDB.Positron) %>%              ### !!! ###
   addPolygons(fillColor = ~pal(`Population,_2010`)  
      ,weight = 1,
  opacity = 1,
  color = "white",
  
 # dashArray = "3",
  fillOpacity = 0.6)

Hover Acation!

leaflet(cluster_outlines)  %>%
  addProviderTiles(providers$CartoDB.Positron) %>%
   addPolygons(fillColor = ~pal(`Population,_2010`)  
      ,weight = 1,
  opacity = 1,
  color = "white",
  fillOpacity = 0.6,
  highlight = highlightOptions(                     ### !!! ###
    weight = 2,                                     ### !!! ###
    fillOpacity = 0.75,                             ### !!! ###
    bringToFront = TRUE)                            ### !!! ###
  )

Pop-ups

labels <- sprintf(
  "<strong>%s</strong><br/>Population: %g",
  cluster_outlines$NBH_NAMES, cluster_outlines$`Population,_2010`
) %>% lapply(htmltools::HTML)



leaflet(cluster_outlines)  %>%
  addProviderTiles(providers$CartoDB.Positron) %>%
   addPolygons(fillColor = ~pal(`Population,_2010`)  
      ,weight = 1,
  opacity = 1,
  color = "white",
  fillOpacity = 0.6,
  
  highlight = highlightOptions(
    weight = 2,
    fillOpacity = 0.75,
    bringToFront = TRUE)
  ,label = labels                                ### !!! ###
  )